<template>
  <div class="data-filling-container">
    <el-form ref="form" :model="formData" :rules="rules" inline>
      <template v-for="(item, index) in formList">
        <el-form-item
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-model="formData[item.prop]"
            :style="item.style || {}"
            :value-format="item.valueFormat"
            :clearable="true"
            :class="item.class"
            :props="item.props"
            :options="item.options"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)"
          >
            <el-option v-if="item.componentType === 'el-select'" v-for="option in item.optionList"
                       :key="option.code"
                       :label="option.name"
                       :value="option.code"
            />
          </component>
        </el-form-item>
      </template>
      <div v-if="selectTypeList.length > 0" style="margin-left: 70px">
        <el-row class="row-title">
          <el-col :span="5">能源名称</el-col>
          <el-col :span="6">用量</el-col>
          <el-col :span="4">单位</el-col>
          <el-col :span="6">碳排放量（kgCO2）</el-col>
          <el-col :span="4"></el-col>
        </el-row>
        <el-row v-for="(item,index) in selectTypeList" :key="item.id" class="row-item">
          <el-col :span="5">{{ item.name }}</el-col>
          <el-col :span="6" style="background: none">
            <el-input v-model="item.usageValue" type="number" :min="0" @blur="usageBlueHandler(item,index)" />
          </el-col>
          <el-col :span="4">{{ item.energyUnit }}</el-col>
          <el-col :span="6">{{ item.carbonEmission }}</el-col>
          <el-col :span="4">
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="() => {
                         selectTypeList.splice(index,1);
                         formData.energyConsumptionTypeIds = formData.energyConsumptionTypeIds.filter(val => val !== item.code)
                       }" />
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import api from '@/api/apis/sceneRoom'
import { parseSceneData } from '@/utils/scene-data'

export default {
  name: 'AddDataFilling',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {},
      selectTypeList: [],
      formList: [
        {
          name: '活动名称',
          prop: 'activityCarbonEmissionId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'ActivityCarbonEmissionSelected'
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          style: { width: '100%' },
          attrConfig: {
            placeholder: '请选择活动名称'
          },
          itemStyle: {
            width: '100%'
          }
        },
        {
          name: '数据时间',
          prop: 'dataStartTime',
          componentType: 'el-date-picker',
          valueFormat: 'yyyy-MM-dd',
          attrConfig: {
            type: 'date',
            format: 'yyyy-MM-dd',
            'value-format': 'yyyy-MM-dd',
            placeholder: '请选择数据时间'
          }

        }, {
          name: '至',
          prop: 'dataEndTime',
          componentType: 'el-date-picker',
          valueFormat: 'yyyy-MM-dd',
          attrConfig: {
            type: 'date',
            format: 'yyyy-MM-dd',
            'value-format': 'yyyy-MM-dd',
            placeholder: '请选择数据时间'
          },
          itemStyle: {}
        },
        {
          name: '所属项目',
          prop: 'sceneProjectId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'SceneProjectSelected'
          },
          itemStyle: {
            width: '100%'
          },
          attrConfig: {
            placeholder: '请选择所属项目',
            options: []
          },
          style: { width: '100%' },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        }, {
          name: '所属场景',
          prop: 'sceneInfo',
          itemStyle: {
            width: '100%'
          },
          style: { width: '100%' },
          componentType: 'el-cascader',
          attrConfig: {
            placeholder: '请选择所属场景'
          },
          options: [],
          props: { checkStrictly: true }
        }, {
          name: '能源种类',
          prop: 'energyConsumptionTypeIds',
          itemStyle: {
            width: '100%'
          },
          style: { width: '100%' },
          componentType: 'el-select',
          optionList: [],
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          attrConfig: {
            multiple: true,
            placeholder: '请选择能源种类'
          },
          options: []
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        activityCarbonEmissionId: [{ required: true, message: '请选择活动名称', trigger: 'blur' }],
        dataStartTime: [{ required: true, message: '请选择数据开始时间', trigger: 'blur' }],
        sceneProjectId: [{ required: true, message: '请选择所属项目', trigger: 'blur' }],
        sceneInfo: [{ required: false, message: '请选择所属场景', trigger: 'blur' }],
        outsourcedCarbonSinks: [{ required: true, message: '请输入外购碳汇', trigger: 'blur' }]
      }
    }
  },
  watch: {
    popData: {
      async handler(data) {
        this.isAdd = !data.dataFillingId
        this.formList.forEach((e) => {
          this.$set(this.formData, e.prop, data[e.prop])
        })
        this.$set(this.formData, 'id', data.dataFillingId)
        let typeList = []
        if (data.dataFillingId) {
          const detailResP = await this.$api.dataFilling.detail(data.dataFillingId)
          typeList = JSON.parse(detailResP.data.detailJson)
          this.$set(this.formData, 'dataStartTime', detailResP.data.dataStartTime)
          this.$set(this.formData, 'dataEndTime', detailResP.data.dataEndTime)
          this.$set(this.formData, 'outsourcedCarbonSinks', detailResP.data.outsourcedCarbonSinks)
          this.$set(this.formData, 'energyConsumptionTypeIds', typeList.map(item => item.energyConsumptionTypeId))
          this.formList[0].attrConfig.disabled = true
          this.formList[1].attrConfig.disabled = true
          this.formList[2].attrConfig.disabled = true
          this.formList[3].attrConfig.disabled = true
          this.formList[4].attrConfig.disabled = true
        }
        if (data.sceneProjectId) {
          await this.getRoomList(data.sceneProjectId)
        }
        const sceneInfo = []
        if (data.sceneEdificeId) {
          sceneInfo.push(data.sceneEdificeId)
        }
        if (data.sceneFloorId) {
          sceneInfo.push(data.sceneFloorId)
        }
        if (data.sceneRoomId) {
          sceneInfo.push(data.sceneRoomId)
        }
        this.$set(this.formData, 'sceneInfo', sceneInfo)
        await this.handlerSelectData(this.formList[0])
        await this.handlerSelectData(this.formList[this.formList.length - 1])
        if (typeList.length > 0) {
          typeList.forEach(item => {
            this.selectTypeList.forEach((selectType, index) => {
              if (selectType.energyConsumptionTypeId === item.energyConsumptionTypeId) {
                this.$set(this.selectTypeList[index], 'carbonEmission', item.carbonEmission)
                this.$set(this.selectTypeList[index], 'usageValue', item.usageValue)
              }
            })
          })
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    async usageBlueHandler(item, index) {
      if (item.usageValue != null && item.usageValue !== '' && this.formData.dataStartTime != null && this.formData.dataEndTime != null) {
        const resp = await this.$api.dataFilling.calculateCarbonEmission(item.code, item.usageValue, this.formData.dataStartTime, this.formData.dataEndTime)
        this.$set(this.selectTypeList[index], 'carbonEmission', resp.data || 0)
      }
    },
    /**
     * change事件
     */
    async handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
      if (config.prop === 'activityCarbonEmissionId') {
        const activityCarbonEmissionId = this.formData[config.prop]
        if (activityCarbonEmissionId == null || activityCarbonEmissionId === '') {
          this.formList = this.formList.filter(item => item.prop !== 'outsourcedCarbonSinks')
        } else {
          const activityCarbonEmission = config.optionList.find(item => item.value === activityCarbonEmissionId)
          if (activityCarbonEmission.baseObj.activityType === '2') { // 碳抵消活动
            const outsourcedCarbonSinks = this.formList.find(item => item.prop === 'outsourcedCarbonSinks')
            if (outsourcedCarbonSinks == null) {
              this.formList.splice(5, 0, {
                name: '外购碳汇（kgCO2）',
                prop: 'outsourcedCarbonSinks',
                componentType: 'el-input-number',
                style: { width: '84%' },
                itemStyle: {
                  width: '100%'
                },
                attrConfig: {
                  min: 0,
                  placeholder: '请输入外购碳汇'
                }
              })
            }
          } else {
            this.formList = this.formList.filter(item => item.prop !== 'outsourcedCarbonSinks')
          }
          await this.loadingEnergyConsumptionTypeList(activityCarbonEmission.baseObj.activityType)
        }
      } else if (config.prop === 'sceneProjectId') {
        // 选择项目后加载场景数据
        this.getRoomList(this.formData[config.prop])
      } else if (config.prop === 'sceneInfo') {
        const roomInfo = this.formData.sceneInfo
        if (roomInfo == null || roomInfo.length === 0) {
          this.formData.sceneEdificeId = null
          this.formData.sceneFloorId = null
          this.formData.sceneRoomId = null
        } else {
          this.formData.sceneEdificeId = roomInfo[0]
          this.formData.sceneFloorId = roomInfo.length > 1 ? roomInfo[1] : null
          this.formData.sceneRoomId = roomInfo.length > 2 ? roomInfo[2] : null
        }
      } else if (config.prop === 'energyConsumptionTypeIds') {
        const energyConsumptionTypeIds = this.formData.energyConsumptionTypeIds
        if (energyConsumptionTypeIds == null || energyConsumptionTypeIds.length === 0) {
          this.selectTypeList = []
        } else {
          this.selectTypeList = this.formList[this.formList.length - 1].optionList.filter(item => energyConsumptionTypeIds.includes(item.code))
        }
      }
    },

    async loadingEnergyConsumptionTypeList(activityType) {
      const result = await this.$api.dataFilling.queryEnergyConsumptionType(activityType)
      const optionList = result.data.map(item => {
        return {
          code: item.id,
          energyConsumptionTypeId: item.id,
          name: item.energyName,
          energyUnit: item.energyUnit
        }
      })
      let item = this.formList[this.formList.length - 1]
      item.optionList = optionList
      this.$set(this.formList, this.formList.length - 1, { ...item })
    },
    async getRoomList(sceneProjectId) {
      let res = await api.queryRoomList({
        sceneProjectId,
        sortColumn: 'floorName',
        sortOrder: 'asc'
      })
      const roomList = parseSceneData(res.data)
      let item = this.formList[4]
      item.options = roomList
      this.$set(this.formList, 4, { ...item })
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          params.detailJson = JSON.stringify(this.selectTypeList)
          const res = await this.$api.dataFilling[this.isAdd ? 'add' : 'update'](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'dataFilling-add')
          }
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-form {
  .el-form-item__content {
    width: 70%;
  }

  .row-title {
    line-height: 28px;
    font-size: 14px;
    font-weight: 600;
    display: flex;
    gap: 2px;
  }

  .row-item {
    line-height: 34px;
    display: flex;
    gap: 2px;
    margin-bottom: 10px;

    .el-col:not(:last-child) {
      background: #DCDFE6;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
